package com.chuanke.ckfamily.job;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.chuanke.ckfamily.service.common.SynizedExcuter;
import com.chuanke.ckfamily.service.common.SysConfigService;
import com.chuanke.ckfamily.service.common.WyService;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.constant.FamilyConstance;
import com.chuanke.ckfamily.service.constant.SysConfigKeyEnum;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.social.FamilyService;

public class FamilyMsgTask {

	private static final Logger log = LoggerFactory.getLogger(FamilyMsgTask.class);

	public static final String QUEUE_NAME = "queue_nickname";

	public static final String FAMILY_TIME = "family_tip_time";

	@Autowired
	private FamilyService familyService;
	
	@Autowired
	private WyService wyService;
	
	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private CacheService cacheService;

	private Random random = new Random();

	/**
	 * 
	 * 催族长发红包消息  家族还有一大波红包没有发，快崔族长发红包吧
	 */
	public void excuteMsg() {
		new SynizedExcuter() {
			@Override
			public void excute() {
				log.debug("开始执行催族长发红包消息业务=====================>");
				FamilyMsgTask.this.sendMsg();
			}
		}.run(cacheService, CacheService.KEY_PREFIX.send_family_msg_.name(), 3000);
	}
	
	private void sendMsg() {
		log.debug("begin send msg");
		Integer family_msg=sysConfigService.getIntegerValue(SysConfigKeyEnum.is_send_family_msg.toString(), FamilyConstance.is_send_family_msg);
		if (family_msg == 1) {
			return;
		}

		Long familyTime = (Long)cacheService.get(FAMILY_TIME);
		if (familyTime != null && familyTime.longValue() > System.currentTimeMillis()) {
			return;
		}

		cacheService.set(FAMILY_TIME, System.currentTimeMillis() + 360000 + random.nextInt(7) * 120000);
		String nickName = getQueueName();
		if (StringUtils.isEmpty(nickName)) {
			return;
		}

		Map<String, Object> param = new HashMap<>();
		List<Map<String, Object>> list = familyService.search(param);
		if(list!=null && !list.isEmpty()){
			for (Map<String, Object> map : list) {
				String owner=MapUtils.getString(map, "owner_user_no");
				String tid=MapUtils.getString(map, "tid");
				Integer mnum=MapUtils.getInteger(map, "mnum");
				log.debug("家族推送 ======》tid={},mnum={},owner={}",tid,mnum,owner);
				if (mnum==null || mnum<=1) {
					continue;
				}

				try {
					wyService.sendMsgForTeam(owner, tid, "恭喜" + nickName + "成功创建家族，成为族长", null, false);
					wyService.sendMsgForTeam(owner, tid, "族长保底收入：300元/月。最高收入可达15000元/月", null, false);
				} catch (CFException e) {
					e.printStackTrace();

				}
			}
		}
	}

	private String getQueueName() {
		if (cacheService.listSize(QUEUE_NAME) == 0) {
			initSize();
		}

		Long size = cacheService.listSize(QUEUE_NAME);
		if (size.longValue() == 0) {
			log.error("can not find nickname for family tips");
			return null;
		}

		return (String)cacheService.index(QUEUE_NAME, random.nextInt(size.intValue()));
	}

	private void initSize() {
		log.debug("load nick name resources");
		InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/chuanke/ckfamily/job/nickname.txt");
		if (is == null) {
			return;
		}

		try {
			try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
				String line = null;
				while ((line = reader.readLine()) != null) {
					log.debug("add nick name ={}", line);
					if (StringUtils.isNotEmpty(line)) {
						cacheService.leftPush(QUEUE_NAME, line.trim());
					}

				}
            }

		} catch (IOException e) {
			e.printStackTrace();

		}
	}

}
